package com.weavernorth.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;


/**
 * 公共工具类
 *
 * @author zm
 * @version V1.0 2019-12-03 created
 */
public class GetShortUtil {
    public static Log log = LogFactory.getLog(GetShortUtil.class.getName());

    /**
     * 获取短地址请求
     * @param strUrl       请求路径
     * @return
     * @throws IOException
     */
    public  String senDealPost(String strUrl) throws IOException {
        log.info("进去方法GetShortUtil的senDealPost");
        String strBody = "";
        try {
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        log.info("创建对象");
        //创建post方式请求对象
        HttpGet httpGet = new HttpGet(strUrl);
        log.info("请求路径:"+strUrl);

        //httpGet【Content-type】、【User-Agent】
        httpGet.setHeader("Content-type", "application/json");


            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpGet);
            //获取状态码
            int strResponseCode=response.getStatusLine().getStatusCode();
            log.info("返回状态=="+strResponseCode);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null&&strResponseCode==200) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
                log.info("返回结果:"+strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }

}

